<template>
	<!-- 编辑弹出框 id,typeId,goodsId,sort -->
	<el-dialog :title="dialogTitle" v-model="dialogVisible" align-center width="50%">
		<el-form ref="theFormRef" :model="dataForm" label-width="100px">
			<el-form-item label="ID"><el-input v-model="dataForm.id" :disabled="true"></el-input></el-form-item>

			<el-form-item label="类别">
				<el-select v-model="dataForm.typeId" placeholder="选择类别"><el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option></el-select>
			</el-form-item>

			<el-form-item label="商品id"><el-input v-model="dataForm.goodsId"></el-input></el-form-item>
			
			<el-form-item label="序号"><el-input v-model="dataForm.sort" type="number"></el-input></el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button size="medium" @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" size="medium" @click="handleSubmit">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup>
// 商品id 的选择 参照轮播配置时 选择商品id的实现
import * as HomeAPI from '@/api/home.js';
import { ref, computed, defineProps, nextTick } from 'vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
	typeId: {
		type: Number,
		default: 2
	},
	typeList: Array //选项数据 [{id:2,name:"为你推荐"},{id:3,name:"新品上线"},{id:4,name:"热销商品"}]
});
const dialogVisible = ref(false); //是否显示
const dataForm = ref({ id: 0 }); //表单
//弹框标题
const dialogTitle = computed(() => {
	return !dataForm.value.id ? '新增' : '编辑';
});

//声明一个模板中DOM元素的引用, 必须和模板里的 ref 同名
const theFormRef = ref(null);
const emit = defineEmits(['refreshDataList']);

const init = async id => {
	dataForm.value.id = id || 0;
	dialogVisible.value = true;
	await nextTick();
	theFormRef.value.resetFields();
	if (id) {
		//是编辑
		let result = await HomeAPI.getDetailById(id);
		dataForm.value = result.data; //看接口文档，知道data是对应的用户对象
	} else {
		//是新增
		setDataFormToDefault();
	}
};

const setDataFormToDefault = () => {
	//初始默认值
	let defaultForm = {};
	defaultForm.id = 0;
	defaultForm.typeId = props.typeId; //Props传递的参数
	defaultForm.goodsId = null;
	defaultForm.sort = 1;
	dataForm.value = Object.assign({}, defaultForm);
};

//提交确认
const handleSubmit = () => {
	theFormRef.value.validate(async valid => {
		if (valid) {
			await HomeAPI.save(dataForm.value);
			ElMessage.success(`保存成功`);
			dialogVisible.value = false;
			emit('refreshDataList'); //重新刷新列表数据
		}
	});
};

//暴露接口方法
defineExpose({
	init
});
</script>

<style scoped></style>
